package com.yonyou.brigade.basic_init.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.toolkit.StringUtils;
import com.nc.utils.HttpUtil;
import com.nc.utils.StringUtil;
import com.yonyou.brigade.basic_init.service.IBaseDocService;
import com.yonyou.brigade.basic_init.service.IUserCenterService;
import com.yonyou.ybzboot.bd.client.BaseDocClient;
import com.yonyou.ybzboot.bd.dto.BdRequestDTO;
import com.yonyou.ybzboot.bd.dto.IServiceType;
import com.yonyou.ybzboot.starter.common.exception.CustomException;
import com.yonyou.ybzboot.starter.common.result.BasicResultCode;
import com.yonyou.ybzboot.starter.facade.result.FacadeResult;
import com.yonyou.ybzboot.uc.dto.UcUserDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 基础档案{@link BaseDocClient}查询服务封装
 *
 * @author kangfw5
 * @since 2019/3/22 09:48
 */
@Service
public class BaseDocServiceImpl implements IBaseDocService {
    private static final Logger logger = LoggerFactory.getLogger(BaseDocServiceImpl.class);

    @Autowired
    private BaseDocClient baseDocClient;

    @Value("${ybz.baseUrl}")
    private String ybzBaseUrl;

    @Value("${ybz.queryRefItemByPks.url}")
    private String url;

    @Autowired
    @Qualifier("userCenterServiceImpl")
    private IUserCenterService userCenterService;

    /**
     * 基础档案{@link BaseDocClient}查询接口
     *
     * @param tenant 租户ID
     * @param org    组织PK
     * @return <code>List<Map<String, String>></code> 职级信息列表
     * @since 2019/3/22 09:48
     */
    @Override
    public List<Map<String, String>> getDutyByTenantAndOrg(String tenant, String org) {
        BdRequestDTO bdRequestDTO = new BdRequestDTO();
        bdRequestDTO.setTenantId(tenant);
        bdRequestDTO.setServiceType(IServiceType.Duty.queryAll);
        List<UcUserDto> userDTOs = userCenterService.getUcUserDtoByOrg(tenant, org);
        if (!CollectionUtils.isEmpty(userDTOs)) {
            bdRequestDTO.setUserId(userDTOs.get(0).getUserId());
        }
        logger.info("调用档案服务查询职务档案，参数：租户{0}组织{1}", tenant, org);
        FacadeResult<List<Map<String, String>>> result = baseDocClient.execute(bdRequestDTO);
        logger.info("调用档案服务查询职务档案，参数：租户{0},组织{1},调用结果{2}", tenant, org, result);
        if (result.isSuccess()) {
            List<Map<String, String>> data = result.getData();
            if (!CollectionUtils.isEmpty(data)) {
                data.remove(0);
                return data;
            } else {
                return null;
            }
        } else {
            return null;
        }
    }

    /**
     * 根据租户查询所有组织（行政组织）
     *
     * @param tenantId 租户ID
     * @param userId   用户ID
     * @return <code>List</code> 组织列表[{"id":"";"code":"";"name":""}]
     */
    @Override
    public List<Map<String, String>> getOrgByTenant(String tenantId, String userId) {
        BdRequestDTO bdRequestDTO = new BdRequestDTO();
        bdRequestDTO.setUserId(userId);
        bdRequestDTO.setTenantId(tenantId);
        bdRequestDTO.setServiceType(IServiceType.SettlementUnit.queryAll);
        FacadeResult<ArrayList<Map<String, String>>> query = baseDocClient.execute(bdRequestDTO);
        // 档案重新部署后可用isSuccess代替判断
        if (query.getCode().equals(BasicResultCode.SUCCESS.getCode())) {
            ArrayList<Map<String, String>> data = query.getData();
            if (com.baomidou.mybatisplus.toolkit.CollectionUtils.isNotEmpty(data)) {
                String id = data.get(0).get("id");
                if (StringUtils.isEmpty(id)) {
                    data.remove(0);
                }
            }
            return data;
        } else {
            logger.error(query.getDetailMsg());
            throw new CustomException(query.getCode(), query.getMsg());
        }
    }

    @Override
    public Map<String, String> getOrgById(String tenantId, String orgId) {
        logger.info("查询组织档案");
        return getDocById(tenantId, orgId, IServiceType.SettlementUnit.queryByIds);
    }

    @Override
    public Map<String, String> getOrgByOsType(String tenantId, String userId, String orgId, String osType) {
        if ("saas".equalsIgnoreCase(osType)){
            return getOrgById(tenantId, orgId);
        }else {
            return getNCOrgById(tenantId, userId, orgId);
        }
    }

    @Override
    public Map<String, String> getNCOrgById(String tenantId, String userId, String orgId) {
        return getNCDocById(tenantId, userId, "业务单元", orgId);
    }




    private Map<String, String> getNCDocById(String tenantId, String userId, String refType, String id){
        logger.info("开始查询NC档案：" + refType);
        JSONObject param = new JSONObject();
        param.put("tenant", tenantId);
        param.put("userId", userId);

        Map<String, Map<String, String>> queryMap = new HashMap();
        Map<String,String> value = new HashMap<>();
        value.put(id, id);
        queryMap.put(refType, value);

        param.put("queryMap", queryMap);
        String rs = "";
        try {
            logger.info("请求报账查询nc档案:" + param.toJSONString());
            rs = HttpUtil.post(ybzBaseUrl + url, param.toJSONString());
            logger.info("查询nc档案结果:" + rs);
            if (StringUtil.isNotEmpty(rs)){
                JSONObject result = JSONObject.parseObject(rs);
                Map<String,Map<String, String>> resultMap = (Map<String, Map<String, String>>) result.get(refType);
                if (resultMap != null){
                    return resultMap.get(id);
                }
                logger.info("查询结果为空");
            }
        }catch (Exception e){
            logger.error("查询nc档案异常：" + e.getMessage());
            e.printStackTrace();
        }
        return null;
    }


    @Override
    public Map<String, String> getDeptById(String tenantId, String deptId) {
        logger.info("查询部门档案");
        return getDocById(tenantId, deptId, IServiceType.Department.queryByIds);
    }

    @Override
    public Map<String, String> getNCDeptById(String tenantId, String userId, String deptId) {
        return getNCDocById(tenantId, userId, "部门", deptId);
    }

    @Override
    public Map<String, String> getDeptByOsType(String tenantId, String userId, String deptId, String osType) {
        if ("saas".equals(osType)){
            return getDeptById(tenantId, deptId);
        }else {
            return getNCDeptById(tenantId, userId, deptId);
        }
    }

    @Override
    public Map<String, String> getProjectById(String tenantId, String projectId) {
        logger.info("查询项目档案");
        return getDocById(tenantId, projectId, IServiceType.Project.queryByIds);
    }

    @Override
    public Map<String, String> getNCProjectById(String tenantId, String userId, String projectId) {
        return getNCDocById(tenantId, userId, "项目", projectId);
    }

    @Override
    public Map<String, String> getInOutProjectByOsType(String tenantId, String userId, String projectId, String osType) {
        if ("saas".equals(osType)){
            return getInOutProjectById(tenantId, projectId);
        }else {
            //这里查询nc的项目，nc的收支项目查询结果返回的key也是 "项目"
            return getNCProjectById(tenantId, userId, projectId);
        }
    }

    @Override
    public Map<String, String> getNCInOutProjectById(String tenantId, String userId, String projectId) {
        return getNCDocById(tenantId, userId, "收支项目", projectId);
    }

    @Override
    public List<Map<String, String>> getProjectByTenant(String tenantId, String userId) {
        logger.info("查询租户项目档案");
       return getDocByTenant(tenantId, userId, IServiceType.Project.queryAll);
    }

    @Override
    public Map<String, String> getInOutProjectById(String tenantId, String projectId) {
        logger.info("查询收支项目档案");
        return getDocById(tenantId, projectId, IServiceType.InOutProject.queryByIds);
    }

    @Override
    public List<Map<String, String>> getInOutProjectByTenant(String tenantId, String userId) {
        logger.info("查询租户收支项目档案");
        return getDocByTenant(tenantId, userId, IServiceType.InOutProject.queryAll);
    }

    private Map<String, String> getDocById(String tenantId, String id, IServiceType serviceType){
        BdRequestDTO bdRequestDTO = new BdRequestDTO();
        Map param = new HashMap();
        List<String> arr = new ArrayList<>();
        arr.add(id);
        param.put("ids", arr);
        bdRequestDTO.setParams(param);
        bdRequestDTO.setTenantId(tenantId);
        bdRequestDTO.setServiceType(serviceType);
        logger.info("调用档案服务查询，参数：Id" + id + "租户 "+tenantId+" 查询类型" + serviceType);
        FacadeResult<ArrayList<Map<String, String>>> query = baseDocClient.execute(bdRequestDTO);
        logger.info("调用档案服务查询：结果:" + query);
        if (query.isSuccess()) {
            List<Map<String, String>> data = query.getData();
            if (!CollectionUtils.isEmpty(data)) {
                return data.get(0);
            } else {
                return null;
            }
        } else {
            logger.error(query.getDetailMsg());
            throw new CustomException(query.getCode(), query.getMsg());

        }
    }

    private List<Map<String, String>> getDocByTenant(String tenant, String userId, IServiceType serviceType){
        BdRequestDTO bdRequestDTO = new BdRequestDTO();
        bdRequestDTO.setUserId(userId);
        bdRequestDTO.setTenantId(tenant);
        bdRequestDTO.setServiceType(serviceType);
        FacadeResult<ArrayList<Map<String, String>>> query = baseDocClient.execute(bdRequestDTO);
        // 档案重新部署后可用isSuccess代替判断
        if (query.getCode().equals(BasicResultCode.SUCCESS.getCode())) {
            ArrayList<Map<String, String>> data = query.getData();
            if (com.baomidou.mybatisplus.toolkit.CollectionUtils.isNotEmpty(data)) {
                String id = data.get(0).get("id");
                if (StringUtils.isEmpty(id)) {
                    data.remove(0);
                }
            }
            return data;
        } else {
            logger.error(query.getDetailMsg());
            throw new CustomException(query.getCode(), query.getMsg());
        }
    }

}
